﻿using AntdUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace TangCaptureTraffic.Manager
{
    internal class ConfigManager
    {
        public static string ConfigFilePath { get; set; } = "config.json";
        public static void LoadConfig()
        {

            if (File.Exists(ConfigFilePath))
            {
                try
                {
                    string json = File.ReadAllText(ConfigFilePath);
                    var config = JsonSerializer.Deserialize<Config>(json);
                    if (config != null)
                    {
                        var memoryConfig=config.MemoryConfig;
                        // 应用配置到MemoryConfig静态类
                        MemoryConfig.EnableAutoMemoryCleanup = memoryConfig.EnableAutoMemoryCleanup;
                        MemoryConfig.MemoryCleanupInterval = memoryConfig.MemoryCleanupInterval;
                        MemoryConfig.MaxSessions = memoryConfig.MaxSessions;
                        MemoryConfig.SessionCleanupCount = memoryConfig.SessionCleanupCount;
                        MemoryConfig.MaxUISessions = memoryConfig.MaxUISessions;
                        MemoryConfig.UISessionCleanupCount = memoryConfig.UISessionCleanupCount;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"加载配置失败: {ex.Message}");
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("配置文件不存在，使用默认配置");
                // 首次运行时保存默认配置
                SaveConfig();
            }
        }

        public static void SaveConfig()
        {
            try
            {
                var memoryConfig = new MemoryConfigData
                {
                    EnableAutoMemoryCleanup = MemoryConfig.EnableAutoMemoryCleanup,
                    MemoryCleanupInterval = MemoryConfig.MemoryCleanupInterval,
                    MaxSessions = MemoryConfig.MaxSessions,
                    SessionCleanupCount = MemoryConfig.SessionCleanupCount,
                    MaxUISessions = MemoryConfig.MaxUISessions,
                    UISessionCleanupCount = MemoryConfig.UISessionCleanupCount,
                    MemoryWarningThreshold = MemoryConfig.MemoryWarningThreshold
                };

                var config = new Config();
                config.MemoryConfig = memoryConfig;

                string json = JsonSerializer.Serialize(config);
                File.WriteAllText(ConfigFilePath, json);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存配置失败: {ex.Message}");
            }
        }
    }
}
